package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoinTask 示例1
 * Fort/Join框架：JDK7，把大任务分为小任务，然后再获取结果。类似于MapReduce的思想。减少线程间的竞争。
 *
 * @author ziyucoding
 * @date 2022-10-27
 **/
@Slf4j
public class ForkJoinTaskExample1 extends RecursiveTask<Integer> {

    public static final int threhold = 2;

    private int start;
    private int end;

    public ForkJoinTaskExample1(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;

        // 如果任务足够小则计算任务
        boolean canCompute = (end - start) <= threhold;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            // 如果任务大于阈值，就分裂成两个子任务计算
            int mid = (start + end) / 2;
            ForkJoinTaskExample1 leftTask = new ForkJoinTaskExample1(start, mid);
            ForkJoinTaskExample1 rightTask = new ForkJoinTaskExample1(mid + 1, end);

            // 执行子任务
            leftTask.fork();
            rightTask.fork();

            // 等待任务执行结束合并其结果
            int leftResult = leftTask.join();
            int rightResult = rightTask.join();

            // 合并子任务
            sum = leftResult + rightResult;
        }

        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        // 生成一个计算任务，计算 1 + 2 + 3 + ... + 10
        ForkJoinTaskExample1 taskExample1 = new ForkJoinTaskExample1(1, 10);
        // 执行一个任务
        Future<Integer> result = forkJoinPool.submit(taskExample1);

        try {
            log.info("result:{}", result.get());
        } catch (InterruptedException e) {
            log.info("InterruptedException", e);
        } catch (ExecutionException e) {
            log.info("ExecutionException", e);
        }
    }
}
